package query;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public enum ConnectionUtils {
    CONNECTION_UTILS;

    public Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://60.205.142.63:3306/how2j?characterEncoding=UTF-8", "root", "root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public List<Hero> list(int start, int count) {
        List<Hero> list = new ArrayList<>();
        Connection connection = ConnectionUtils.CONNECTION_UTILS.getConnection();
        System.out.println("connection1 = " + connection);
        try (
                Statement statement = connection.createStatement();
        ) {
            ResultSet resultSet = statement.executeQuery("select id,name,hp from hero LIMIT " + start + " offset " + count);
            while (resultSet.next()) {
                Hero hero = new Hero();
                hero.setId(resultSet.getInt("id"));
                hero.setName(resultSet.getString("name"));
                hero.setHp(resultSet.getFloat("hp"));
                list.add(hero);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<Hero> list1(int currentPage, int count) {
        int start = (currentPage - 1) * count;
        List<Hero> list = new ArrayList<>();
        Connection connection = ConnectionUtils.CONNECTION_UTILS.getConnection();
        System.out.println("connection2 = " + connection);
        try (
                Statement statement = connection.createStatement();
        ) {
//            String sql = "select id,name,hp from hero LIMIT " + count + " offset " + start;
            String sql = "select id,name,hp from hero LIMIT " + start + " , " + count;
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                Hero hero = new Hero();
                hero.setId(resultSet.getInt("id"));
                hero.setName(resultSet.getString("name"));
                hero.setHp(resultSet.getFloat("hp"));
                list.add(hero);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
